package pri.jz.keeper.ui.content

import android.app.Application
import android.util.Log
import androidx.lifecycle.viewModelScope
import androidx.navigation.NavGraph.Companion.findStartDestination
import androidx.navigation.NavHostController
import kotlinx.coroutines.flow.*
import pri.jz.keeper.repository.UserRepository
import pri.jz.keeper.ui.base.BaseViewModel
import pri.jz.keeper.ui.uistate.ContentState
import pri.jz.keeper.ui.uistate.ContentViewState

/**
 *Author by: JZ
 *Email: 2451756617@qq.com
 *PS:
 */
class ContentViewModel(application: Application) : BaseViewModel(application) {
    //用于数据初始化状态加载的界面切换
    private val _viewState = MutableStateFlow(ContentViewState.DEFAULT)
    val viewState = _viewState.asStateFlow()

    private val _state = MutableStateFlow<ContentState>(ContentState.Default)
    val state = _state.asStateFlow()

    private val userRepository = UserRepository.getIns()
    val user = userRepository.user

    //加载初始数据
    fun initLoading(userId: Int) {
        setViewState(ContentViewState.LOADING)
        requestLaunch(
            networkTask = {
                userRepository.loadUser(userId)
            },
        )
        //需要处理初始化
        setViewState(ContentViewState.DEFAULT)
    }

    /**
     * 重新加载
     */
    fun reLoad() {

        initLoading(userRepository.userId)
    }

    fun setState(state: ContentState) {
        if (_state.value != state) {
            _state.value = state
            _state.value = ContentState.Default
        }
    }

    private fun setViewState(viewState: ContentViewState) {
        _viewState.value = viewState
    }


    //底部导航栏点击事件
    fun onNavigateClick(navController: NavHostController,screenLabel: String) {
        navController.navigate(screenLabel) {
            popUpTo(navController.graph.findStartDestination().id) {
                saveState = true
            }
            //当选择的目标为栈顶元素时，不会复用目标
            launchSingleTop = true
            //是否保存当前目标，以便再次选择时复用
            restoreState = true
        }
    }

}